package org.west.sky.scripture.imports.core.base;

import lombok.Getter;
import lombok.Setter;

import java.io.PrintWriter;
import java.io.StringWriter;

@Getter
@Setter
public class Result<T> {

    private static final int OK = 0;

    private int resultCode;

    private T data;

    private String message;

    private String exception;

    private static <T> Result<T> restResult(int code, T data, String msg) {
        Result<T> result = new Result<>();
        result.setResultCode(code);
        result.setData(data);
        result.setMessage(msg);
        return result;
    }

    public static <T> Result<T> error(int code, String message, Throwable e) {
        Result<T> result = new Result<>();
        result.setResultCode(code);
        result.setMessage(message);
        StringWriter string = new StringWriter();
        e.printStackTrace(new PrintWriter(string));
        result.setException(string.toString());
        return result;
    }

    public static <T> Result<T> ok() {
        return restResult(OK, null, "操作成功");
    }

    public static <T> Result<T> ok(T data) {
        return restResult(OK, data, "操作成功");
    }

    public static <T> Result<T> ok(T data, String message) {
        return restResult(OK, data, message);
    }

    public static <T> Result<T> error(int code) {
        return restResult(code, null, "操作失败");
    }

    public static <T> Result<T> error(int code, String message) {
        return restResult(code, null, message);
    }

    public static <T> Result<T> customize(int code, T data, String msg) {
        return restResult(code, data, msg);
    }
}
